package com.zkingsoft.actions.common;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zkingsoft.constance.SystemConstance;
import com.zkingsoft.model.Function;
import com.zkingsoft.model.RolePwoer;
import com.zkingsoft.model.Users;
import com.zkingsoft.plugin.util.EncrypUtil;
import com.zkingsoft.plugin.util.RandomValidateCode;
import com.zkingsoft.plugin.util.WebUtil;
import com.zkingsoft.pojo.AjaxResult;
import com.zkingsoft.pojo.UserPwoer;
import com.zkingsoft.services.CompanyService;
import com.zkingsoft.services.FunctionService;
import com.zkingsoft.services.RolePwoerService;
import com.zkingsoft.services.UsersService;
import com.zkingsoft.syslog.SysLog;
import com.zkingsoft.syslog.SysLogService;

/**
 * @description 通用控制器,本action未经session过验证器
 * @author 姜友瑶
 * @email 935090232@qq.com
 * @date 2016-06-26
 */
@RequestMapping(value = "/common")
@Controller
public class CommonController extends BaseController {

	@Resource
	private UsersService usersService;
	@Resource
	private FunctionService functionService;
	@Resource
	private RolePwoerService rolePwoerService;

	@Resource
	private CompanyService companyService;
	@Resource
	private SysLogService logService;

	/**
	 * 
	 * @Description: 页面定向方法，每个权限模块公用一个，每个模块共享一个一级路径，已便于进行权限过滤
	 * @author:姜友瑶
	 * @param page1
	 *            文件夹
	 * @param page2
	 *            页面名称
	 * @return 返回类型 String
	 * @date 2016年8月30日
	 */
	@RequestMapping(value = "/redirect/{page1}/{page2}")
	public String redirect(@PathVariable("page1") String page1, @PathVariable("page2") String page2) {
		return "common/" + page1 + "/" + page2;
	}

	/**
	 * 
	 * @Description: 页面定向方法，每个权限模块公用一个，每个模块共享一个一级路径，已便于进行权限过滤
	 * @author:姜友瑶
	 * @param page1
	 *            页面名称
	 * @return 返回类型 String
	 * @date 2016年8月30日
	 */
	@RequestMapping(value = "/redirect/{page1}")
	public String redirect(@PathVariable("page1") String page1) {
		return "common/" + page1;
	}

	/**
	 * 
	 * @Description: 向页面输出一个验证码，并存放在session中 session取验证码名称
	 *               RandomValidateCode.RANDOMCODEKEY
	 * @author:姜友瑶
	 * @param request
	 * @param response
	 *            返回类型 void
	 * @date 2016年8月30日
	 */
	@RequestMapping(value = "/validateImg")
	public void messagelistiIn(HttpServletRequest request, HttpServletResponse response) {
		RandomValidateCode.newValidateImg(request, response);
	}

	/**
	 * 
	 * @Description: 登录验证
	 * @author:姜友瑶
	 * @param user
	 * @param request
	 * @return 返回类型 AjaxResult
	 * @date 2016年8月30日
	 */
	@RequestMapping(value = "/dologin")
	public @ResponseBody AjaxResult dologin(Users user, HttpServletRequest request) {
		// 是否同时有账号和密码
		if (user.getAccount() != null && user.getPassword() != null) {
			// 加密密码
			try {
				user.setPassword(EncrypUtil.getMD5(user.getPassword()));
			} catch (UnsupportedEncodingException e) {
				return new AjaxResult(AjaxResult.STATUS_ERR, null, "登录失败");
			}
			List<Users> users = usersService.findByModel(user);
			// 执行数据库查询
			if (users != null && users.size() > 0) {
				user = users.get(0);
				// 账号状态判断
				if (user.getIsDeleted().equals(SystemConstance.DELETED_N)) {

					if (user.getAccountStatus() != null
							&& !user.getAccountStatus().equals(SystemConstance.ACCOUNT_STATUS_INACTIVATED)) {
						// 激活状态
						if (user.getAccountStatus().equals(SystemConstance.ACCOUNT_STATUS_ACTIVATE)) {
							// 获取操作内容
							SysLog log = new SysLog();
							log.setOperation(SysLog.OPERATION_LOGIN);
							log.setIp(WebUtil.getRequest().getRemoteAddr());
							log.setUserName(user.getName());
							log.setUserId(user.getId());
							log.setCreatedate(new Date());
							log.setContent("登录了Martrix系统");
							logService.add(log);
							// 账号类型判断
							return typeHandeler(user, request);

						} else if (user.getAccountStatus().equals(SystemConstance.ACCOUNT_STATUS_LOCKED)) {
							return new AjaxResult(AjaxResult.STATUS_ERR, null, "账号已经锁定");
						}
					} else {
						return new AjaxResult(AjaxResult.STATUS_ERR, null, "账号未激活");
					}
				} else {
					return new AjaxResult(AjaxResult.STATUS_ERR, null, "账号已被删除");
				}

			} else {
				return new AjaxResult(AjaxResult.STATUS_ERR, null, "账号或密码错误");
			}
		} else {
			return new AjaxResult(AjaxResult.STATUS_ERR, null, "请输入账号和密码");
		}
		return new AjaxResult(AjaxResult.STATUS_ERR, null, "请输入账号和密码");
	}

	/**
	 * 根据用户类型不同进行不同的处理
	 * 
	 * @param user
	 * @param request
	 * @return
	 */
	private AjaxResult typeHandeler(Users user, HttpServletRequest request) {

		// 如果不是超级管理员
		if (!user.getUserType().equals(SystemConstance.USER_TYPE_SUPER)) {
			WebUtil.getSession().setAttribute("company", companyService.findById(user.getCompanyId()));
		}

		// 开发人员
		if (user.getUserType().equals(SystemConstance.USER_TYPE_DEVELOPER)) {
			request.getSession().setAttribute("user", user);
			return new AjaxResult(AjaxResult.STATUS_OK, "developer/redirect/index", null);
		} else if (user.getUserType().equals(SystemConstance.USER_TYPE_SUPER)) {
			// 超级管理员
			request.getSession().setAttribute("user", user);
			return new AjaxResult(AjaxResult.STATUS_OK, "super/redirect/index", null);
			// 企业管理员
		} else if (user.getUserType().equals(SystemConstance.USER_TYPE_ADMIN)) {
			request.getSession().setAttribute("user", user);
			// 获取用户所有的权限信息
			UserPwoer userPwoer = getUserPwoer(user);
			request.getSession().setAttribute("userPwoer", userPwoer);
			return new AjaxResult(AjaxResult.STATUS_OK, "admin/redirect/index", null);
			// 企业用户
		} else if (user.getUserType().equals(SystemConstance.USER_TYPE_EMPLOYEE)) {
			request.getSession().setAttribute("user", user);
			// 获取用户所有的权限信息
			UserPwoer userPwoer = getUserPwoer(user);
			request.getSession().setAttribute("userPwoer", userPwoer);
			return new AjaxResult(AjaxResult.STATUS_OK, "admin/redirect/index", null);
			// 普通用户
		} else if (user.getUserType().equals(SystemConstance.USER_TYPE_EMPLOYEE)) {
			request.getSession().setAttribute("user", user);
			return new AjaxResult(AjaxResult.STATUS_OK, "admin/redirect/index", null);
		}
		return new AjaxResult(AjaxResult.STATUS_ERR, "common/redirect/login", "什么鬼！");
	}

	/**
	 * 获取用户操作权限
	 * 
	 * @param user
	 * @return
	 */
	private UserPwoer getUserPwoer(Users user) {
		UserPwoer userPwoer = new UserPwoer();
		// 公司用户 **过滤个人权限
		if (user.getUserType().equals(SystemConstance.USER_TYPE_EMPLOYEE)) {
			RolePwoer rpQuery = new RolePwoer();
			rpQuery.setRoleId(user.getRoleId());
			List<RolePwoer> rolePwoerList = rolePwoerService.findByModel(rpQuery);
			Map<Long, RolePwoer> powers = new HashMap<>();
			for (RolePwoer rolePwoer : rolePwoerList) {
				powers.put(rolePwoer.getFunctionId(), rolePwoer);
			}
			userPwoer.setPowers(powers);
			List<Function> functions = new ArrayList<>();
			List<Function> topFunction = functionService.findRoleFunctionByGrade(user.getRoleId(), 1);
			for (Function function : topFunction) {
				function.setChildenFunctions(
						functionService.selectRoleFunctionByParent(user.getRoleId(), function.getId()));
				functions.add(function);
			}
			userPwoer.setFunctions(functions);

			// 公司管理员的权限等于公司权限 ** 过滤公司权限
		} else if (user.getUserType().equals(SystemConstance.USER_TYPE_ADMIN)) {
			List<Function> functions = new ArrayList<>();
			Function fnQuery = new Function();
			fnQuery.setGrade(1);
			List<Function> topFunctions = functionService.filterFunction(functionService.findByModel(fnQuery),
					user.getCompany());
			for (Function topFunction : topFunctions) {
				fnQuery.setGrade(null);
				fnQuery.setParentId(topFunction.getId());
				topFunction.setChildenFunctions(
						functionService.filterFunction(functionService.findByModel(fnQuery), user.getCompany()));
				functions.add(topFunction);
			}
			userPwoer.setFunctions(functions);
			Map<Long, RolePwoer> powers = new HashMap<>();
			for (Function function : functions) {
				for (Function childenfunction : function.getChildenFunctions()) {
					RolePwoer rolePwoer = new RolePwoer();
					rolePwoer.setBtns(childenfunction.getBtns());
					powers.put(childenfunction.getId(), rolePwoer);
				}
			}
			userPwoer.setPowers(powers);
		}
		return userPwoer;
	}

	/**
	 * 用户退出系统
	 * 
	 * @param
	 * @throws @date
	 *             2015-11-30 11:35
	 * @author Matrix-J
	 */

	@RequestMapping(value = "/loginOut")
	public String loginOut(HttpSession session, HttpServletResponse response) throws Exception {
		session.invalidate();
		return "redirect:/common/redirect/login";
	}

}